package com.hnkywl.sts.service.jhgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.jhgl.BgjhhzDao;
import com.hnkywl.sts.dao.jhgl.BgjhhzmxDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.entity.jhgl.Bgjhhz;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.webservice.bg.request.SendPlanImportResult;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ZHUCHG
 * Date: 13-7-2
 * Time: 上午9:57
 * To change this template use File | Settings | File Templates.
 */
@Service
public class BgjhhzService {
    private BgjhhzDao bgjhhzDao;
    private BgjhhzmxDao bgjhhzmxDao;
    private GsjgDao gsjgDao;

    public Bgjhhz find(Long id) {
        return bgjhhzDao.get(id);
    }

    public String findGyzList(String type, Long jhdwId, Long gyzId, Integer jhnf, Integer jhyf, String wzbm, Date startDate, Date endDate, String sm, String gyzsbcl, int pageNo, int pageSize) {
        Page<Map> page = bgjhhzDao.findList(type, jhdwId, gyzId, jhnf, jhyf, wzbm, sm, startDate, endDate, gyzsbcl, pageNo, pageSize);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String json = gson.toJson(page.getResult());
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
    }

    public String findBgjhhzList(String sm,String bm,Date startDate,Date endDate, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        if (endDate != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(endDate);
            c.add(Calendar.DATE,1);
            endDate = c.getTime();
        }
        Page<Bgjhhz> bgjjhzPage = this.bgjhhzDao.findBgjhhzList(sm,bm,startDate,endDate, pageNo, pageSize);
        String bgjjhzJson = gson.toJson(bgjjhzPage.getResult());
        return "{\"total\":" + bgjjhzPage.getTotalCount() + ",\"rows\":" + bgjjhzJson + "}";
    }

    public String findMxList(Long id, Integer zt) {
        List<Map> list = bgjhhzmxDao.findList(id, zt);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        String json = gson.toJson(list);
        return "{\"rows\":" + json + "}";
    }


    //供应站计划处理完成
    @Transactional
    public void gyzclwc(Long id) {
        boolean flag = bgjhhzmxDao.gyzwclmx(id, 1);
        if (!flag) {
            Bgjhhz bgjhhz = bgjhhzDao.get(id);
            bgjhhz.setZt(3);
            bgjhhz.setLastUpdated(new Date());
        }
    }

    //业务科计划处理完成
    @Transactional
    public void ywkclwc(Long id) {
        boolean flag = bgjhhzmxDao.gyzwclmx(id, 3);
        if (!flag) {
            Bgjhhz bgjhhz = bgjhhzDao.get(id);
            bgjhhz.setZt(4);
            bgjhhz.setLastUpdated(new Date());
        }
    }

    public String findBgjhhzmxContent(Long id) {
        Gson gson = new Gson();
        List<Map> bgjhhzmxList = this.bgjhhzmxDao.findBgjhhzmxContent(id);
        Double sbjs = 0d;
        Double sbsl = 0d;
        Double hsj = 0d;
        Double bhsj = 0d;
        Double hsje = 0d;
        for (Map map : bgjhhzmxList) {
            sbjs += map.get("sbjs") == null ? 0d : Double.parseDouble(map.get("sbjs").toString());
            sbsl += map.get("sbsl") == null ? 0d : Double.parseDouble(map.get("sbsl").toString());
            hsj += map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString());
            bhsj += map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString());
            hsje += map.get("hsje") == null ? 0d : Double.parseDouble(map.get("hsje").toString());
        }
        String json = gson.toJson(bgjhhzmxList);
        return "{\"rows\":" + json + ",\"footer\":[{\"cd.z\":\"合计:\",\"sbjs\":" + sbjs + ",\"sbsl\":" + sbsl + ",\"hsj\":" + hsj + ",\"bhsj\":" + bhsj + ",\"hsje\":" + hsje + "}]}";
    }

    // 更新是否完成
    @Transactional
    public void updateSfcg(List<Bgjhhzmx> bgjhhzmxList, List<SendPlanImportResult> resultList) {
        Map<Long, String> errorReasonMap = new HashMap<Long, String>();
        for (SendPlanImportResult s : resultList) {
            errorReasonMap.put(s.getDetailId(), s.getErrorReason());
        }
        Bgjhhzmx bgjhhzmxTemp;
        for (Bgjhhzmx bgjhhzmx : bgjhhzmxList) {
            bgjhhzmxTemp = this.bgjhhzmxDao.get(bgjhhzmx.getId());
            if (isInResultList(bgjhhzmx.getId(), resultList)) {
                bgjhhzmxTemp.setSfcg(0);
                bgjhhzmxTemp.setZt(0);
                bgjhhzmxTemp.setCcyy(errorReasonMap.get(bgjhhzmx.getId()));
            } else {
                bgjhhzmxTemp.setSfcg(1);
                bgjhhzmxTemp.setZt(6);
                bgjhhzmxTemp.setCcyy("");
            }
            bgjhhzmxTemp.setLastUpdated(new Date());
            this.bgjhhzmxDao.save(bgjhhzmxTemp);
        }
    }

    //判断保供计划明细的Id是否在返回的列表中，存在则该条明细导入不成功
    private boolean isInResultList(Long id, List<SendPlanImportResult> resultList) {
        for (SendPlanImportResult s : resultList) {
            if (id.longValue() == s.getDetailId().longValue()) {
                return true;
            } else {
                continue;
            }
        }
        return false;
    }

    //借口不通，产生异常时调用，将数据置为"业务科已处理"状态，并且保存异常信息
    @Transactional
    public void dealWhenExcept(List<Bgjhhzmx> bgjhhzmxList, String exception) {
        Bgjhhzmx bgjhhzmxTemp;
        for (Bgjhhzmx bgjhhzmx : bgjhhzmxList) {
            bgjhhzmxTemp = this.bgjhhzmxDao.get(bgjhhzmx.getId());
            bgjhhzmxTemp.setSfcg(0);
            bgjhhzmxTemp.setZt(4);
            bgjhhzmxTemp.setClsj(new Date());
            bgjhhzmxTemp.setCcyy(exception);
            this.bgjhhzmxDao.save(bgjhhzmxTemp);
        }
    }

    // 计划明细开始导入
    @Transactional
    public void updateKsdr(List<Bgjhhzmx> bgjhhzmxList) {
        Bgjhhzmx bgjhhzmxTemp;
        for (Bgjhhzmx bgjhhzmx : bgjhhzmxList) {
            bgjhhzmxTemp = this.bgjhhzmxDao.get(bgjhhzmx.getId());
            if (bgjhhzmxTemp.getZt() >= 5)
                throw new RuntimeException("计划正在导入或已经导入，请刷新数据重试!");
            bgjhhzmxTemp.setZt(5);
            this.bgjhhzmxDao.save(bgjhhzmxTemp);
        }
    }

    /**
     * 查询计划单位
     *
     * @param bgjhhzId
     * @return
     */
    public Gsjg getJhdwByBgjhhz(Long bgjhhzId) {
        String gsjgSql = "select ts.id  from t_biz_bgjhhz t,t_sys_gsjg  ts where ts.id = t.jhdw_id and ts.deleted=0 and t.id = ?";
        List gsjgList = this.bgjhhzmxDao.findBySQL(gsjgSql, bgjhhzId);
        if (null != gsjgList && gsjgList.size() > 0) {
            BigDecimal objectId = (BigDecimal) gsjgList.get(0);
            Gsjg gsjg = this.gsjgDao.get(Long.valueOf(objectId.toString()));
            return gsjg;
        }
        return null;
    }

    @Autowired
    public void setBgjhhzDao(BgjhhzDao bgjhhzDao) {
        this.bgjhhzDao = bgjhhzDao;
    }

    @Autowired
    public void setBgjhhzmxDao(BgjhhzmxDao bgjhhzmxDao) {
        this.bgjhhzmxDao = bgjhhzmxDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
}
